package com.edu.koudingmusic.fragments;


import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.andraskindler.quickscroll.QuickScroll;
import com.edu.koudingmusic.BaseApplication;
import com.edu.koudingmusic.MainActivity;
import com.edu.koudingmusic.R;
import com.edu.koudingmusic.activities.MusicPlayActivity;
import com.edu.koudingmusic.adapters.MyMusicListAdapter;
import com.edu.koudingmusic.entities.Mp3Info;
import com.edu.koudingmusic.services.PlayService;
import com.edu.koudingmusic.tools.MediaUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyMusicListFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener {


    private static final String TAG = "MyMusicListFragment";
    private ListView mListView;

    private ArrayList<Mp3Info> mMp3Infos;

    private MainActivity mMainActivity;

    private MyMusicListAdapter mMyMusicListAdapter;
    private ImageView mAlbumImage;
    private ImageView mMusicPause;
    private ImageView mMusicNext;
    private TextView mMusicName;
    private TextView mMusicSinger;
    private int currentPosition = 0;
    private QuickScroll mQuickScroll;

    public MyMusicListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mMainActivity = (MainActivity) context;

    }

    public static MyMusicListFragment newInstance() {
        MyMusicListFragment fragment = new MyMusicListFragment();
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my_music_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        mListView = (ListView) view.findViewById(R.id.listView_my_music);
        mAlbumImage = (ImageView) view.findViewById(R.id.imageView_album);
        mMusicName = (TextView) view.findViewById(R.id.songName);
        mMusicSinger = (TextView) view.findViewById(R.id.singer);
        mMusicPause = (ImageView) view.findViewById(R.id.my_music_play_pause);
        mMusicNext = (ImageView) view.findViewById(R.id.my_music_next);

        mQuickScroll = (QuickScroll) view.findViewById(R.id.quickscroll);
        mMusicPause.setOnClickListener(this);
        mMusicNext.setOnClickListener(this);
        mAlbumImage.setOnClickListener(this);

        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e(TAG, "onResume: 绑定服务");
        // 绑定服务
        mMainActivity.bindPlayService();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 解绑服务
        mMainActivity.unBindPlayService();
    }

    //加载本地音乐列表
    public void loadData() {

        mMp3Infos = MediaUtils.getMp3Infos(mMainActivity);
        // 用于同步音乐
        mMyMusicListAdapter = new MyMusicListAdapter(mMainActivity, mMp3Infos);
        mListView.setAdapter(mMyMusicListAdapter);
        mListView.setOnItemClickListener(this);
        initQuickScroll();
    }

    private void initQuickScroll() {

        mQuickScroll.init(QuickScroll.TYPE_INDICATOR_WITH_HANDLE,mListView,mMyMusicListAdapter,QuickScroll.STYLE_HOLO);

        mQuickScroll.setFixedSize(1);
        mQuickScroll.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 48);

        mQuickScroll.setPopupColor(QuickScroll.BLUE_LIGHT,QuickScroll.BLUE_LIGHT_SEMITRANSPARENT,1, Color.WHITE,1);


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mMainActivity.mPlayService.getChangeList() != PlayService.MY_MUSIC_LIST) {
            mMainActivity.mPlayService.setMp3Infos(mMp3Infos);
            mMainActivity.mPlayService.setChangeList(PlayService.MY_MUSIC_LIST);
        }
        mMainActivity.mPlayService.play(position);

        // 保存播放时间
        savePlayRecord();
    }

    private void savePlayRecord() {

        Mp3Info mp3Info = mMainActivity.mPlayService.getMp3Infos().get(mMainActivity.mPlayService.getCurrentPosition());
        try {
            BaseApplication mApp = (BaseApplication) mMainActivity.getApplication();
            Mp3Info playRecordMp3Info = mApp.sDbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId", "=", mp3Info.getId()));
            if (playRecordMp3Info == null) {
                mp3Info.setMp3InfoId(mp3Info.getId());
                // 设置当前播放时间
                mp3Info.setPlayTime(System.currentTimeMillis());
                mApp.sDbUtils.save(mp3Info);
                Log.e(TAG, "onClick: save");
            } else {
                playRecordMp3Info.setPlayTime(System.currentTimeMillis());
                mApp.sDbUtils.update(playRecordMp3Info, "playTime");
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    // 回调播放状态下的 ui 设置
    public void changeUIStatusOnPlay(int position) {
        // 用当前播放的 mMp3Infos
        if (position >= 0 && position < mMainActivity.mPlayService.getMp3Infos().size()) {
            Mp3Info mp3Info = mMainActivity.mPlayService.getMp3Infos().get(position);
            mMusicName.setText(mp3Info.getTitle());
            mMusicSinger.setText(mp3Info.getArtist());
            if (mMainActivity.mPlayService.isPlaying()) {
                mMusicPause.setImageResource(R.mipmap.pause);
            } else {
                mMusicPause.setImageResource(R.mipmap.play);
            }
            // TODO: 2016/2/24 需要问一下老师
            // 这边有点问题，拿不到图片，我想的是没有对应的图片。
            /*Bitmap albumImage = MediaUtils.getArtwork(mMainActivity, mp3Info.getId(), mp3Info.getAlbumId(), true, true);
            mAlbumImage.setImageBitmap(albumImage);*/
            mAlbumImage.setImageResource(R.mipmap.music_album);
            currentPosition = position;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_music_play_pause:
                if (mMainActivity.mPlayService.isPlaying()) {
                    mMusicPause.setImageResource(R.mipmap.player_btn_play_normal);
                    mMainActivity.mPlayService.pause();
                } else {
                    if (mMainActivity.mPlayService.isPause()) {
                        mMusicPause.setImageResource(R.mipmap.player_btn_pause_normal);
                        mMainActivity.mPlayService.start();
                    } else {
                        // 这边可以进记录
                        mMainActivity.mPlayService.play(mMainActivity.mPlayService.getCurrentPosition());
                    }
                }
                break;
            case R.id.my_music_next:
                mMainActivity.mPlayService.next();
                break;

            case R.id.imageView_album:
                Intent intent = new Intent(mMainActivity, MusicPlayActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
}
